<template>
	<view class="" style="width: 100vw;height: 100vh">
		<view class="" :style="{'background':kbackgroundColor2}" style="min-height: 100vh">
		<hx-navbar title="充值" :back="true" :fixed="false" :color="knavTitleColor" :style="{backgroun:kbackgroundColor2}"
			barPlaceholder="hidden" transparent="auto"></hx-navbar>
		<view class="content">
			<view class="box_bk"
				:class="[{'border_sel_box_black':ktheme =='black'},{'border_sel_box_purple':ktheme =='purple'}]">
				<view class="">
					为了您的资金安全，金世界仅提供对公账户充值。
				</view>
				<view class="box_mess">
					<view class="">对公账户名称： </view>
					<view class="">金世界（北京）科技有限公司 </view>
				</view>
				<view class="box_mess">
					<view style="width: 30%;">银行对公账户： </view>
					<view style="width: 69%;" @click="dialogConfirm">{{company}}</view>
				</view>
				<view class="box_mess">
					<view style="width: 22%;">开户银行： </view>
					<view style="width: 76%;">上海浦东发展银行股份有限公司北京安华桥支行</view>
				</view>
				<view class="box_mess">
					<view class="">客服电话： </view>
					<view class="">010-67520714</view>
				</view>
				<view class="box_mess">
					<view class="">汇款凭证：</view>
					<view class="" v-if="file!=''">
						<image :src="file" @click="previewImage()"  style="width: 130rpx;height: 70rpx;" mode=""></image>
					</view>
					<view class="voucher"  v-if="file==''" @click="uploadImage"
						:style="{'background': (ktheme != 'purple' ? '#434343':' #E5E5E5')}">上传图片</view>
				</view>
				<view class="box_mess">
					<view class="">汇款金额：</view>
					<view class=""><input @confirm="onInput" type="number" v-model="money" class="box_input"></view>
				</view>
			</view>

		</view>
		<view class="bth">
			<view class="btntk" @click="fullClick" :style="{background:kbuttonBgColor}">
				立即充值
			</view>

		</view>
		<uni-popup ref="ticfPopup" type="center" :maskBackgroundColor="'rgba(0,0,0,0.5)'">
			<view class="store-view store-border-all tips-padding"
				:style="{'background':kbackgroundColor,color:knormalColor}"
				:class="[{'alert-border-black':ktheme =='black'},{'alert-border-purple':ktheme =='purple'}]">
				<text class="popup-title">提示</text>
				<text class="popup-subtitle">
					提交成功，审核通过后将可充值
				</text>
			</view>
		</uni-popup>
		</view>
	</view>
</template>

<script>
	import {
		apiBaseUrl
	} from '@/config/config.js';
	export default {
		data() {
			return {
				company:"91180078801000001051",
				voucherImg: '',
				money: "",
				file: ""
			}
		},
		onPullDownRefresh() {
			setTimeout(function() {
				uni.stopPullDownRefresh()
			}, 1000)
		},
		methods: {
			dialogConfirm() {
				let that = this
				uni.setClipboardData({
					data: this.company,
					success() {
						that.$common.errorToShow('已复制剪贴板')
					},
					fail(r) {
					}
				})
			},
		   previewImage() {  
		      uni.previewImage({  
		        current: this.file, 
		        urls: [this.file], 
		        success: function (res) {  
		        },  
		        fail: function (err) {  
		         this.$common.errorToShow(err)
		        }  
		      });  
		    }  ,
			//失去焦点调用
			onInput(e) {
				let value = e.detail.value;
				// 使用正则表达式匹配整数  
				const reg = /^\d+$/;
				if (!reg.test(value)) {
					// 如果不是整数，则阻止输入  

					this.$common.errorToShow('请输入汇款金额!')
				} else {
					this.money = e.detail.value
				}
			},
			fullClick() {
				if(this.file==''){
					this.$common.errorToShow('请上传图片!')
				}else if (this.money == '' ) {
					this.$common.errorToShow('请输入汇款金额!')
				} else {
					var data={
						amount:this.money,
						proof:this.file
					}
					this.$api.purseSavePicture(data,res => {
						if(res.status){
							this.$refs.ticfPopup.open()
							setTimeout(function(){
								uni.redirectTo({
									url:'/pages/user/wallet_system/pay_detail'
								})
							},3000)
							
						}else{
								this.$common.errorToShow(res.message)
						}
					})
				}

			},
			// upload(filePath) {
			// 	var _this = this
			// 	uni.chooseImage({
			// 		count: 1, // 默认9  
			// 		sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有  
			// 		sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
			// 		success: function(res) {
			// 			const tempFilePaths = res.tempFilePaths;
			// 	_this.uploadImage(tempFilePaths[0]); // 假设只选择了一张图片 
			// 		}
			// 	});
			// },
			// uploadImage(filePath) {
			// 	console.log("filePath-", filePath);
			// 	var _this=this
			// 	var url = apiBaseUrl + 'purse/purseExtractTopup/saveTopup?' + this.money + this.file
			// 	let token = this.$db.get('userToken')
			// 	uni.uploadFile({
			// 		url: url, // 仅为示例，并非真实的接口地址  
			// 		filePath: filePath,
			// 		fileType: 'image',
			// 		name: 'file',
			// 		header: {
			// 			'Authorization': 'Bearer ' + token
			// 		},
			// 		success: (res) => {
			// 			console.log("uploadFileRes00", JSON.parse(res.data));
			// 			let data = JSON.parse(res.data);
			// 			_this.file =data.data.data;
			// 			console.log(_this.file ); // 这里是服务器返回的数据  
			// 		},
			// 		fail: (error) => {
			// 			_this.$common.errorToShow(error)
			// 		}
			// 	});
			// }
			uploadImage() {
				let _this = this
				// this.photoType = type
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						let filePath = tempFilePaths[0]
						//#ifdef APP-IOS || APP-ANDROID
						const theme = uni.getStorageSync('theme');
						let color = theme == 'purple' ? "#000000" : "#ffffff"
						let style = theme == 'purple' ? "black" : "white"
						var styles = {
							color: color,
							background: "rgba(0,0,0,0.0)",
							style: style,
						}
						var waiting = plus.nativeUI.showWaiting("上传中...", styles);
						_this.uploadFile(filePath)
						//#endif
						// #ifndef APP-IOS || APP-ANDROID
						uni.showLoading({
							title: '上传中...'
						});
						_this.afterRead(tempFilePaths)
						// #endif
					}
				});
			},
			uploadFile(filePath) {
				var _this = this
				var url = apiBaseUrl + 'purse/purseExtractTopup/saveTopup?' + this.file
				let token = this.$db.get('userToken')
				uni.uploadFile({
					url: url, // 仅为示例，并非真实的接口地址  
					filePath: filePath,
					fileType: 'image',
					name: 'file',
					header: {
						'Authorization': 'Bearer ' + token
					},
					success: (res) => {
						// console.log("uploadFileRes00", JSON.parse(res.data));
						let data = JSON.parse(res.data);
						_this.file = data.data.data;
						//#ifdef APP-PLUS
						plus.nativeUI.closeWaiting();
						//#endif
						uni.hideLoading();
					},
					fail: (error) => {
						_this.$common.errorToShow(error)
						//#ifdef APP-PLUS
						plus.nativeUI.closeWaiting();
						//#endif
						uni.hideLoading();
					},
					complete: () => {
						//#ifdef APP-PLUS
						plus.nativeUI.closeWaiting();
						//#endif
						uni.hideLoading();
					}
				});
			},
			//压缩
			recursionCompressH5(url) {
				return new Promise((resolve, reject) => {
					this.recursionCompress(url, resolve)
				})
			},
			// 传入blob路径，.then()获取blob文件
			httpRequest(src) {
				let that = this
				return new Promise((resolve, reject) => {
					let xhr = new XMLHttpRequest()
					xhr.open('GET', src, true)
					xhr.responseType = 'blob'
					xhr.onload = function(e) {
						if (this.status == 200) {
							let myBlob = this.response
							let files = new window.File(
								[myBlob],
								myBlob.type, {
									type: myBlob.type
								}
							) // myBlob.type 自定义文件名
							resolve(files)
						} else {
							reject(false)
						}
					}
					xhr.send()
				})
			},
			recursionCompress(url, resolve) {
				let _this = this
				uni.getImageInfo({
					src: url,
					success(res) {
						let canvasWidth = res.width; //图片原始长宽
						let canvasHeight = res.height;
						let img = new Image();
						img.src = res.path;
						let canvas = document.createElement("canvas");
						let ctx = canvas.getContext("2d");
						canvas.width = canvasWidth / 2;
						canvas.height = canvasHeight / 2;
						ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
						canvas.toBlob(function(fileSrc) {
							let imgSrc = window.URL.createObjectURL(fileSrc);
							uni.getFileInfo({
								filePath: imgSrc,
								success: (resFileInfo) => {
									console.log(imgSrc, 'resFileInfo', resFileInfo)
									if (resFileInfo.size > 1024 * 1024) {
										//压缩后大于1M就继续压缩
										console.log('再次压缩')
										_this.recursionCompress(imgSrc, resolve);
										// indexObj.recursionCompressH5(imgSrc, callback, item);
										return;
									} else {
										resolve(imgSrc)
									}
								},
							});
						});
					}
				});
			},
			afterRead(e) {
				let _this = this
				const file = e
				// 遍历图片资源
				file.map(item => {
					// 进行压缩图片
					this.recursionCompressH5(item).then(url => {
						_this.httpRequest(url).then(res => {
							const fileReader = new FileReader()
							fileReader.readAsDataURL(
								res
							) // 读取blob类型的图像文件（不是blob路径），读取成功触发onload方法，并得到result（base64格式的图片）
							fileReader.onload = (event) => {
								if (fileReader.result) {
									// 上传最终压缩之后的图片
									_this.uploadFile(fileReader.result).then(res => {
										// this.fileList.push(res)
									}).catch(() => {
										//#ifdef APP-PLUS
										plus.nativeUI.closeWaiting();
										//#endif
										uni.hideLoading();
									})
									// 调用wx_uploadImage接口，图片大小必须是1M以下，否则报错
									// wx_uploadImage({
									//   image: fileReader.result
									// }).then(res => {
									//   console.log('上传图片成功', res)
									//   this.image = res.storage_path
									// })
								}
							}
						})
					})
				})
			},


		}
	}
</script>

<style scoped lang="scss">
	.content {
		margin: auto;
	}

	.box_bk {
		margin: auto;
		width: 690rpx;
		margin-top: 33rpx;
		padding: 25rpx 18rpx;
		border-radius: 10rpx;
		border: 4rpx solid transparent;
		font-size: 26rpx;
	}

	.border_sel_box_black {
		color: white;
		width: 690rpx;
		border: 4rpx solid transparent;
		background-clip: padding-box, border-box;
		background-origin: padding-box, border-box;
		border-radius: 20rpx;
		background-image: linear-gradient(to bottom, #000000, #0b0b0b), linear-gradient(180deg, #F5F97F, #55CC7C);
		// padding: 10rpx 24rpx;
	}

	.border_sel_box_purple {
		color: #000;
		width: 687rpx;
		border: 4rpx solid transparent;
		background-clip: padding-box, border-box;
		background-origin: padding-box, border-box;
		border-radius: 20rpx;
		background-image: linear-gradient(to bottom, #ffffff, #ffffff), linear-gradient(0deg, #7776FF, #AE2CF1);
	}

	.box_mess {
		display: flex;
		margin-top: 32rpx;
		align-items: flex-start;
	}

	.box_input {
		border: 1px solid #7D7D7D;
		padding: 5rpx;
	}

	.voucher {
		width: 182rpx;
		height: 68rpx;
		background: #434343;
		line-height: 67rpx;
		text-align: center;
		border-radius: 8rpx;
	}

	.bth {
		position: fixed;
		bottom: 90rpx;
		left: 32%;

	}

	.btntk {
		width: 270rpx;
		height: 88rpx;
		margin: 10rpx auto;
		border-radius: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		color: #fff;
		font-weight: 400;
	}
</style>